#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "interface.h"


static int fd = 0;
static int keyflag = 0;

void init_daemon(void)
{

    int pid;
    int i;
    if(pid=fork())
        exit(0);        //是父进程，结束父进程
    else if(pid< 0)
        exit(1);        //fork失败，退出
    //是第一子进程，后台继续执行
    setsid();           //第一子进程成为新的会话组长和进程组长
    //并与控制终端分离
    if(pid=fork())
        exit(0);        //是第一子进程，结束第一子进程
    else if(pid< 0)

        exit(1);        //fork失败，退出

    //是第二子进程，继续

    //第二子进程不再是会话组长
    for(i=0;i< NOFILE;++i)  //关闭打开的文件描述符
        close(i);
    chdir("/tmp");      //改变工作目录到/tmp
    umask(0);           //重设文件创建掩模
	printf("shouhu jincheng chuangjian chenggong\r\n");
    return;

}

char *getpnum()
{
	int ret = 0;
	int nfd;
	int buf_size = 50;
	char read_buf[buf_size];
	char *pnum = (char *)malloc(4*11);
	
	nfd = open("/phonenum.txt", O_RDONLY);//打开文件描述符
	if(nfd < 0)
	{
		perror("open file error!");
		return;
	}
	
	ret = read(nfd, read_buf, buf_size);
	if(0 > ret)
	{
		perror("read file error!");
		return;
	}
	strncpy(pnum, read_buf, 11);
	
	printf("pnum:%s\n", pnum);
	return pnum;
}

void handle(int sig)
{
	int keyValue = 0;
	//收到信号，处理信号
	if (read(fd, &keyValue, sizeof(keyValue)) > 0)
	{
		sleep(1);
		char *pnum = getpnum();	//get_pnum()函数用来获取电话号码
		if(86 == keyValue)
		{
			if(keyflag!=0)
			{
				return;
			}
			keyflag++;
			printf("key 2 down, id=%d\r\n", keyValue);
			sendmsg_api(1, pnum);
			keyflag = 0;
		}
		else if(87 == keyValue)
		{
			if(keyflag!=0)
			{
				return;	
			}
			keyflag++;
			printf("key 3 down, id=%d\r\n", keyValue);
			sendmsg_api(0, pnum);
			keyflag = 0;
		}
	}
}

int main()
{
	init_daemon();
	//open
	fd = open("/dev/key_dev0", O_RDWR);
	if (fd < 0)
	{
		perror("open error");
		return -1;
	}
	//安装中断 
	signal(SIGIO, handle);
	
	//设置属主
	fcntl(fd, F_SETOWN, getpid());
	
	//支持异步通信
	int flag = fcntl(fd, F_GETFL); 
	fcntl(fd, F_SETFL, flag | FASYNC);
	
	//做自己的事
	printf("do something\r\n");
	while(1);
		
	//close
	close(fd);
	return 0;
}
